Skip to content

fix(build): recover ConfigDumpInfo after failed Designer build - #47

Open
korolevpavel wants to merge 10 commits into
alkoleft:masterfrom
korolevpavel:fix/issue-24-cdfi-rollback
Open

fix(build): recover ConfigDumpInfo after failed Designer build#47
korolevpavel wants to merge 10 commits into
alkoleft:masterfrom
korolevpavel:fix/issue-24-cdfi-rollback

Conversation

@korolevpavel

@korolevpavel korolevpavel commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

Closes #24.

  • snapshots tracked ConfigDumpInfo.xml before Designer load and restores it byte-for-byte on load/update failure, pre-update cancellation, or deadline expiry;
  • exposes typed recovery diagnostics in CLI JSON and MCP, including cleanup warnings and retained artifacts;
  • preserves recovery diagnostics across multi-source-set Designer and EDT failures.

Verification:

  • cargo test --bin v8-runner cdfi_recovery -- --format terse (13 passed)
  • cargo test --test cli_build -- --format terse (20 passed)
  • focused helpers/build/domain/MCP suites passed (12/12, 50/50, 2/2, 2/2)
  • cargo fmt --all -- --check; cargo check --all-targets; git diff --check

Known baseline: two pre-existing compiler warnings and repository-wide strict-clippy debt remain outside this change.

Summary by CodeRabbit

  • Новые возможности

    • Добавлено автоматическое восстановление ConfigDumpInfo.xml после сбоев или отмены Designer-сборки.
    • В результатах сборки и CLI/MCP-выводе отображается статус восстановления, путь к резервной копии, количество изменений и предупреждения.
    • Содержимое и формат исходного файла сохраняются без изменений.
  • Документация

    • Добавлены инструкции и техническое описание сценариев восстановления и диагностики.
  • Исправления

    • Предотвращено сохранение частично изменённого ConfigDumpInfo.xml после неудачной сборки.

- keep isolated worktree directories out of version control
- define transactional snapshot and recovery boundaries\n- split successful reconcile into issue alkoleft#46
- define test-first recovery tasks\n- include verification and review gates
- snapshot tracked ConfigDumpInfo before Designer load\n- restore raw bytes without XML rewriting
- persist snapshots after failed restoration\n- use durable atomic CDFI replacement
- recover snapshots on load and update failure paths
- retain platform output after successful update
- expose typed recovery status in build results
- document failed-build source protection
- expose truthful typed recovery diagnostics on success and failure
- preserve cleanup warnings and retained recovery artifacts
- cover idempotent and absent-baseline recovery paths
@coderabbitai

coderabbitai Bot commented Jul 26, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@korolevpavel, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 21 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d533f8e6-720b-497c-bae8-d083a80cecc1

📥 Commits

Reviewing files that changed from the base of the PR and between 9fcb661 and f2d9629.

📒 Files selected for processing (1)
  • tests/cli_build.rs

Walkthrough

Добавлен механизм byte-exact snapshot и восстановления ConfigDumpInfo.xml при сбоях Designer-сборки. Recovery-результаты передаются через BuildResult, отображаются в CLI/MCP и покрываются модульными и CLI-тестами.

Changes

Восстановление CDFI

Layer / File(s) Summary
Контракт восстановления и результат сборки
docs/superpowers/..., src/domain/build.rs
Описаны сценарии восстановления и добавлены CdfiRecoverySummary, CdfiRecoveryAction и поле BuildResult.cdfi_recovery.
Снимок и восстановление CDFI
src/use_cases/build_project/cdfi_recovery.rs
Реализованы snapshot, подсчёт изменений, атомарное восстановление, удаление созданного файла и cleanup с предупреждениями.
Интеграция guard в Designer-конвейер
src/use_cases/build_project.rs, src/use_cases/build_project/coordinator.rs, src/use_cases/build_project/helpers.rs
Designer-шаги используют recovery guard, структурированные результаты и агрегацию recovery-диагностики по этапам сборки.
Вывод диагностики и проверки
src/cli/execute.rs, src/mcp/service.rs, tests/cli_build.rs, SKILL/SKILL.md, .gitignore
CLI/MCP и JSON-тесты отражают CDFI recovery, документация описывает диагностику, а .worktrees/ добавлена в игнорируемые пути.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant BuildProject
  participant CdfiRecoveryGuard
  participant Designer
  participant BuildResult
  participant CLIorMCP
  BuildProject->>CdfiRecoveryGuard: capture ConfigDumpInfo.xml
  BuildProject->>Designer: execute Designer load
  Designer-->>BuildProject: build outcome
  BuildProject->>CdfiRecoveryGuard: restore or cleanup
  CdfiRecoveryGuard-->>BuildResult: cdfi_recovery summary
  BuildResult-->>CLIorMCP: serialized recovery diagnostics
Loading

Suggested reviewers: alkoleft

Poem

Я, кролик, snapshot в норку принёс,
CDFI вернул — не случился занос.
Designer споткнулся — файл цел и чист,
В JSON засиял recovery-лист.
Прыг-скок — и сборка снова в пути!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Добавление .worktrees/ в .gitignore не связано с восстановлением ConfigDumpInfo и выглядит как постороннее изменение. Удалите или вынесите .gitignore-правку в отдельный PR, если она не нужна для этой задачи.
Docstring Coverage ⚠️ Warning Docstring coverage is 72.06% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Название кратко и точно описывает восстановление ConfigDumpInfo после сбоя Designer build.
Linked Issues check ✅ Passed Изменения реализуют snapshot/restore ConfigDumpInfo, typed recovery diagnostics и cleanup warnings для failure-путей Designer, что соответствует #24.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
src/use_cases/build_project/cdfi_recovery.rs (1)

108-149: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Повторный вызов restore() после успешного восстановления вернёт ошибку.

После finalize_successful_restore snapshot удалён, поэтому повторный restore() (если guard когда-нибудь переиспользуют) упадёт в restore_snapshot_with на чтении снимка вместо возврата NotNeeded. Сейчас вызывающий код делает это один раз, но защита от будущего рефакторинга дешёвая: помечать guard как «уже восстановлен» и сразу отдавать NotNeeded.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/use_cases/build_project/cdfi_recovery.rs` around lines 108 - 149,
Добавьте в состояние guard признак успешного восстановления и обновляйте его
после завершения restore; в restore_with проверяйте этот признак до обращения к
snapshot и возвращайте CdfiRecoverySummary с действием NotNeeded. Используйте
существующие значения tracked_path, original_exists и changed_entry_count, чтобы
повторный вызов restore() не пытался читать уже удалённый snapshot.
src/use_cases/build_project.rs (1)

632-645: 🗄️ Data Integrity & Integration | 🔵 Trivial | 🏗️ Heavy lift

Диагностика восстановления хранится только для одного source-set.

BuildResult.cdfi_recovery — один слот, а retain_cdfi_recovery/merge_cdfi_recovery в координаторе перезаписывают предыдущее значение (тест execute_build_keeps_designer_cdfi_replacement_after_successful_update явно ожидает summary для ext, а не для main). При сборке нескольких source-set сведения о предыдущих CDFI теряются, кроме склеенного cleanup-предупреждения. Если это осознанный компромисс — ок; иначе стоит перейти на Vec<CdfiRecoverySummary> в контракте.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/use_cases/build_project.rs` around lines 632 - 645, Измените контракт
результата сборки вокруг BuildStepOutcome и BuildResult::cdfi_recovery с одного
Option<CdfiRecoverySummary> на Vec<CdfiRecoverySummary>, чтобы сохранять
диагностику для каждого source-set. Обновите retain_cdfi_recovery и
merge_cdfi_recovery в координаторе для добавления новых сведений вместо
перезаписи предыдущих, сохранив существующее объединение cleanup-предупреждений.
src/use_cases/build_project/coordinator.rs (1)

986-999: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

retain_cdfi_recovery теряет второе cleanup-предупреждение.

Если у текущего summary уже есть cleanup_warning, кандидат отбрасывается целиком — включая его собственный cleanup_warning и удержанный snapshot_path. merge_cdfi_recovery в такой ситуации предупреждения склеивает; логично переиспользовать её и на успешном пути.

♻️ Возможный вариант
 fn retain_cdfi_recovery(
     current: &mut Option<Box<CdfiRecoverySummary>>,
     candidate: Option<Box<CdfiRecoverySummary>>,
 ) {
     let Some(candidate) = candidate else {
         return;
     };
-    if current
-        .as_ref()
-        .is_none_or(|summary| summary.cleanup_warning.is_none())
-    {
-        *current = Some(candidate);
-    }
+    *current = merge_cdfi_recovery(current.take(), Some(candidate));
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/use_cases/build_project/coordinator.rs` around lines 986 - 999, Update
retain_cdfi_recovery so a candidate is not discarded when the current summary
already has cleanup_warning; merge both summaries through merge_cdfi_recovery,
preserving the candidate’s cleanup warning and snapshot_path. Keep the existing
replacement behavior when current is absent or has no cleanup warning, and
retain the early return for a missing candidate.
docs/superpowers/plans/2026-07-26-cdfi-rollback.md (1)

56-59: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

\n в git commit -m не превратится в перевод строки.

В двойных кавычках bash оставит \n буквально; используйте $'...' или несколько -m. То же в шагах Task 2 и Task 3.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/plans/2026-07-26-cdfi-rollback.md` around lines 56 - 59,
Исправьте команды git commit в текущем шаге и шагах Task 2 и Task 3:
последовательность \n внутри двойных кавычек сейчас сохраняется буквально, а не
становится переносом строки. Используйте несколько аргументов -m либо ANSI-C
quoting через $'...', сохранив заданное содержимое сообщения коммита.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/cli_build.rs`:
- Around line 414-453: Update
build_json_failure_reports_successful_cdfi_recovery and its write_build_script
setup so the /LoadConfigFromFiles path mutates ConfigDumpInfo.xml before the
build fails, causing actual recovery. Change the cdfi_recovery assertion to
expect action "restored", while retaining the final byte-for-byte comparison
with original_cdfi.

---

Nitpick comments:
In `@docs/superpowers/plans/2026-07-26-cdfi-rollback.md`:
- Around line 56-59: Исправьте команды git commit в текущем шаге и шагах Task 2
и Task 3: последовательность \n внутри двойных кавычек сейчас сохраняется
буквально, а не становится переносом строки. Используйте несколько аргументов -m
либо ANSI-C quoting через $'...', сохранив заданное содержимое сообщения
коммита.

In `@src/use_cases/build_project.rs`:
- Around line 632-645: Измените контракт результата сборки вокруг
BuildStepOutcome и BuildResult::cdfi_recovery с одного
Option<CdfiRecoverySummary> на Vec<CdfiRecoverySummary>, чтобы сохранять
диагностику для каждого source-set. Обновите retain_cdfi_recovery и
merge_cdfi_recovery в координаторе для добавления новых сведений вместо
перезаписи предыдущих, сохранив существующее объединение cleanup-предупреждений.

In `@src/use_cases/build_project/cdfi_recovery.rs`:
- Around line 108-149: Добавьте в состояние guard признак успешного
восстановления и обновляйте его после завершения restore; в restore_with
проверяйте этот признак до обращения к snapshot и возвращайте
CdfiRecoverySummary с действием NotNeeded. Используйте существующие значения
tracked_path, original_exists и changed_entry_count, чтобы повторный вызов
restore() не пытался читать уже удалённый snapshot.

In `@src/use_cases/build_project/coordinator.rs`:
- Around line 986-999: Update retain_cdfi_recovery so a candidate is not
discarded when the current summary already has cleanup_warning; merge both
summaries through merge_cdfi_recovery, preserving the candidate’s cleanup
warning and snapshot_path. Keep the existing replacement behavior when current
is absent or has no cleanup warning, and retain the early return for a missing
candidate.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6ba8b1a0-360f-428a-a4d4-62178eb3abc9

📥 Commits

Reviewing files that changed from the base of the PR and between d612e2d and 9fcb661.

📒 Files selected for processing (12)
  • .gitignore
  • SKILL/SKILL.md
  • docs/superpowers/plans/2026-07-26-cdfi-rollback.md
  • docs/superpowers/specs/2026-07-26-cdfi-rollback-design.md
  • src/cli/execute.rs
  • src/domain/build.rs
  • src/mcp/service.rs
  • src/use_cases/build_project.rs
  • src/use_cases/build_project/cdfi_recovery.rs
  • src/use_cases/build_project/coordinator.rs
  • src/use_cases/build_project/helpers.rs
  • tests/cli_build.rs

Comment thread tests/cli_build.rs
@zeegin

zeegin commented Aug 4, 2026

Copy link
Copy Markdown

А точно надо восстановление? Может его вообще в игнор?

я в юнике политику прописывал другую

https://github.com/IngvarConsulting/unica/blob/7e4ba7df73602da8d4256a7a7497849772560bd5/plugins/unica/skills/v8-runner/SKILL.md?plain=1#L284

По факту с каждой базой в каждой соурстри у каждого разраба будет свое состояние файла

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(build): transactional snapshot/rollback ConfigDumpInfo.xml on failed build

2 participants